<script setup lang="ts">
import { ArrowLeftBold,Refresh,Delete } from '@element-plus/icons-vue'
import router from '@/router';
import { reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import {login,getCode,register,resetPassword} from '@/api/login';
import { useUserStore } from '@/stores/index' // 引入用户状态管理
import {ElMessage} from 'element-plus'
import { onUnmounted } from 'vue';
defineOptions({
  name: 'LoginIndex'
});
const ruleFormRef = ref<FormInstance>()
const ifShow = ref<number>(4) // 控制表单显示与隐藏
// 倒计时相关状态
const countdown = ref(0);
const timer = ref<number | null>(null);
const countdownRef = ref<HTMLButtonElement | null>(null) // 获取验证码按钮引用

// 密码验证函数
const validatePass = (rule: unknown, value: string, callback: (error?: Error) => void) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    callback()
  }
}
// 昵称名验证函数
const validateAdmin = (
  rule: unknown,
  value: string,
  callback: (error?: Error) => void
) => {
  if (value === '') {
    callback(new Error('请输入昵称名'))
  } else {
    callback()
  }
}

const ruleForm = ref({
  pass: '123456',
  admin: 'admin',
  email: 'ty2495641631@qq.com', // 邮箱字段
  code: '' // 验证码字段
})

//
const rules = reactive<FormRules<typeof ruleForm>>({
  pass: [{ validator: validatePass, trigger: 'blur' }],
  admin: [{ validator: validateAdmin, trigger: 'blur' }],
})


// 组件卸载时清除定时器
onUnmounted(() => {
  if (timer.value) clearInterval(timer.value);
});
// 获取验证码函数
const getRegisterCode = async () => {
  ElMessage.success('验证码发送中，请稍候...')
  try {
    const res = await getCode({ email: ruleForm.value.email }) as {
      code: number; 
      message: string 
    };
    
    console.log('验证码发送结果:', res);
    
    if (res.code === 200) {
      // 1. 正确显示消息
      ElMessage.success('验证码已发送，请注意查收');
      // 2. 启动倒计时
      countdown.value = 60;
      // 3. 使用响应式变量控制按钮状态
      if (countdownRef.value) {
        countdownRef.value.disabled = true;
      }
      // 4. 设置定时器（带清除机制）
      timer.value = setInterval(() => {
        countdown.value--;
        
        if (countdown.value <= 0) {
          // 倒计时结束
          if (timer.value) clearInterval(timer.value);
          if (countdownRef.value) {
            countdownRef.value.disabled = false;
          }
        }
      }, 1000);
    }
  } catch (error) {
    console.error('验证码发送失败:', error);
    ElMessage.error('验证码发送失败，请重试');
  }
};

// 提交表单
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  // 根据前端预定义的规则: 验证表单
   formEl.validate(async (valid) => {
    if (valid) {
      console.log('submit!')
      // 发送请求
      if (ifShow.value === 1) {
        // 注册表单提交逻辑
        const res = await register({
          username: ruleForm.value.admin,
          email: ruleForm.value.email,
          password: ruleForm.value.pass,
          code: ruleForm.value.code
        })as { code: number; message: string }
        console.log('注册结果:', res);
        if (res.code === 200) {
          // 注册成功后跳转到登录页面
          ElMessage.success('注册成功，请登录');
          ifShow.value = 4; // 切换到登录表单
        } else {
          // 注册失败，显示错误信息
          ElMessage.error(res.message || '注册失败，请重试');
        }

      } else if (ifShow.value === 2) {
        // 找回密码表单提交逻辑
        const res = await resetPassword({
          username: ruleForm.value.admin,
          email: ruleForm.value.email,
          password: ruleForm.value.pass,
          code: ruleForm.value.code
        }) as { code: number; message: string }
        console.log('找回密码结果:', res);
        if (res.code === 200) {
          // 找回密码成功后跳转到登录页面
          ElMessage.success('密码重置成功，请登录');
          ifShow.value = 4; // 切换到登录表单
        } else {
          // 找回密码失败，显示错误信息
          ElMessage.error(res.message || '找回密码失败，请重试');
        }

      } else if (ifShow.value === 3) {
        // 二维码登录表单提交逻辑

      } else if (ifShow.value === 4) {
        // 账号密码登录表单提交逻辑
        console.log('登录信息:', ruleForm.value.admin, ruleForm.value.pass)
        const res = await login({ username: ruleForm.value.admin, password: ruleForm.value.pass }) as { 
          code: number; message: string;
           data?: { token: string } }

        console.log('登录结果:', res)
        if (res.code === 200 && res.data && res.data.token) {
          // 登录成功后跳转到首页
          // 存储token到本地
          const useStore = useUserStore()
          useStore.setToken(res.data.token)
          const t =  localStorage.getItem('pinia_token')
          console.log('Token已存储??',  t)
        
          router.push('/layout/home')
        } else {
          // 登录失败，显示错误信息
          console.error(res.message)
        }
      }
    }
  })
}
// 表单重置函数 
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

// 切换表单类型函数
const switchForm = (type: number) => {
  // 这里可以根据 type 切换不同的表单显示
  // 例如 1: 注册, 2: 找回密码
  // 你可以根据实际需求设置显示的表单
  // 这里只是一个占位函数，防止报错
  console.log('切换表单类型:', type)
  if (type === 1) {
    // 切换到注册表单
    ifShow.value = 1; // 假设 1 是注册表单的标识
  } else if (type === 2) {
    // 切换到找回密码表单
    ifShow.value = 2; // 假设 2 是找回密码表单的标识
  }else if (type === 3) {
    // 切换到二维码登录表单
    ifShow.value = 3; // 假设 3 是二维码登录表单的标识
  }else if (type === 4) {
    if(type === ifShow.value){  // 如果当前已经是账号密码登录表单
      ifShow.value = 3; // 切换到3二维码登录表单
      return;
    }
    // 切换到账号密码登录表单
    ifShow.value = 4; // 假设 4 是账号密码登录表单的标识
  }
}

</script>

<template>
    <div class="login-container">
        <!-- 登录表单 -->
        <div class="login-form">
            <!-- 按钮返回和切换 -->
             <div class="button-container">
                <!-- 回到首页 -->
                <div class="button1">
                        <el-button  @click="router.push('/layout/home')"  circle>
                            <el-icon><ArrowLeftBold /></el-icon>
                        </el-button>
                </div>
                <!-- 切换登录方式 -->
                <div class="button2">
                        <el-button circle @click="switchForm(4)">
                            <el-icon><Refresh /></el-icon>
                        </el-button>
                </div>
             </div>
       
            <!-- 账号密码登录表单 -->
            <div class="form-container" v-if="ifShow === 4">
               <h2>账号密码登录</h2>
               <p>欢迎登录，请输入账号和密码</p>
               <!-- 表单 -->
                <el-form
                    ref="ruleFormRef"
                    style="max-width: 600px"
                    :model="ruleForm"
                    status-icon
                    :rules="rules"
                    label-width="auto"
                    class="demo-ruleForm"
                   
                >
                    <!-- 昵称名和密码输入框 -->       
                  <el-form-item label="昵称" prop="admin">
                          <el-input v-model="ruleForm.admin" type="text" autocomplete="off"/>
                    </el-form-item>
                    <el-form-item label="密码" prop="pass">
                        <el-input v-model="ruleForm.pass" type="password" autocomplete="off" />
                    </el-form-item>
                    <el-form-item >
                        <el-button type="primary" @click="submitForm(ruleFormRef)" >
                            登录
                        </el-button>
                        <el-button @click="resetForm(ruleFormRef)">取消</el-button>
                    </el-form-item>
                </el-form>
                <!-- 注册和找回密码 -->
                 <div class="demo2-ruleForm">
                    <el-button
                        type="primary"
                        link
                        @click="switchForm(1)"
                        >
                        注册账号
                    </el-button>
                    <el-button
                        type="primary"
                        link
                         @click="switchForm(2)"
                        >
                        找回密码
                    </el-button>
                 </div>
            </div>

            <!-- 二维码登录和其他登录表单 -->
            <div class="form-container" v-if="ifShow === 3">
                <h2>二维码登录</h2>
                <p>请使用手机扫描二维码登录</p>
                <!-- 二维码图片 -->
                <div class="qr-code">
                    <img src="../../assets/charts/qr-code.png" alt="二维码登录" >
                </div>
                <!-- 其他登录 -->
                <div class="other-login">
                 <p>或使用以下方式登录</p>
                  <div class="two-login">
                        <el-button type="primary" :icon="Delete" />

                  </div>
                
                </div>

            </div>


            <!-- 注册表单 -->
            <div class="form-container" v-if="ifShow === 1">
                <h2>注册账号</h2>
                <p>欢迎注册，请输入账号和密码</p>
                <!-- 表单 -->
                <el-form
                    ref="ruleFormRef"
                    style="max-width: 600px"
                    :model="ruleForm"
                    status-icon
                    :rules="rules"
                    label-width="auto"
                    class="demo-ruleForm"
                >

                    <el-form-item label="昵称" prop="admin" >
                        <el-input v-model="ruleForm.admin" type="text" autocomplete="off" placeholder="请输入昵称"/>
                    </el-form-item>
                    <el-form-item label="邮箱" prop="mail" >
                        <el-input v-model="ruleForm.email" type="text" autocomplete="off" placeholder="请输入邮箱"/>
                    </el-form-item>

                     <el-form-item label="验证码" prop="VCode">
                        <el-input v-model="ruleForm.code" type="text" style="width: 196.42px;" placeholder="请输入验证码">
                          <template v-slot:append>
                            <el-button ref="countdownRef"  :disabled="countdown > 0"
                              @click = "getRegisterCode">

                              {{ countdown > 0 ? `${countdown}秒后重试` : '发送验证码' }}

                            </el-button>

                          </template>
                        </el-input>
                     </el-form-item>

                    <el-form-item label="密码" prop="pass">
                        <el-input v-model="ruleForm.pass" type="password" autocomplete="off" placeholder="请输入密码"/>
                    </el-form-item>

                    <el-form-item >
                        <el-button type="primary" @click="submitForm(ruleFormRef)" >
                            注册
                        </el-button>
                        <el-button @click="resetForm(ruleFormRef)">取消</el-button>
                    </el-form-item>
                     <el-button
                        type="primary"
                        link
                         @click="switchForm(4)"
                        >
                        返回登录
                    </el-button>
                </el-form>
            </div>

            <!-- 忘记密码表单 -->
            <div class="form-container" v-if="ifShow === 2">
                <h2>找回密码</h2>
                <p>请输入注册时的邮箱或手机号</p>
                <!-- 表单 -->
                <el-form
                    ref="ruleFormRef"
                    style="max-width: 600px"
                    :model="ruleForm"
                    status-icon
                    :rules="rules"
                    label-width="auto"
                    class="demo-ruleForm"
                >
                    <el-form-item label="昵称" prop="admin" >
                        <el-input v-model="ruleForm.admin" type="text" autocomplete="off" placeholder="请输入昵称"/>
                    </el-form-item>
                   <el-form-item label="邮箱" prop="email" >
                        <el-input v-model="ruleForm.email" type="text" autocomplete="off" placeholder="请输入注册邮箱"/>
                    </el-form-item>

                     <el-form-item label="验证码" prop="VCode">
                        <el-input v-model="ruleForm.code" type="text" style="width: 196.42px;" placeholder="请输入验证码">
                          <template v-slot:append>
                            <el-button ref="countdownRef"  :disabled="countdown > 0"
                              @click = "getRegisterCode">

                              {{ countdown > 0 ? `${countdown}秒后重试` : '发送验证码' }}
                            </el-button>
                          </template>
                        </el-input>
                     </el-form-item>
                    <el-form-item label="新密码" prop="pass">
                        <el-input v-model="ruleForm.pass" type="password" autocomplete="off" placeholder="请输入新密码"/>
                    </el-form-item>
                    
                    <el-form-item >
                        <el-button type="primary" @click="submitForm(ruleFormRef)" >
                            找回密码
                        </el-button>
                        <el-button @click="resetForm(ruleFormRef)">重置密码</el-button>
                    </el-form-item>
                </el-form>
                <el-button
                    type="primary"
                    link
                      @click="switchForm(4)"
                    >
                    返回登录
                </el-button>
            </div>
    </div>
</div>
</template>

<style scoped lang="scss">  
.login-container {
    // 全屏
    position: fixed;// 以整个浏览器为标准、定位到视口
    // 覆盖整个视口
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    //内容居中
    display: flex;
    align-items: center;
    justify-content: center;

    background: url('../../assets/charts/loginbgi.png') no-repeat;

    background-size: cover;// 背景图像覆盖整个容器
    background-position: center;// 背景图像居中显示
}
.login-form{
    display: flex;
    flex-direction: column; // 竖直方向布局
    justify-content: center; // 内容垂直居中

    width: 400px;
    padding: 20px;
    background-color: rgba(255, 255, 255, 0.8); // 半透明白色背景
    border-radius: 10px; // 圆角边框
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1); // 阴影效果

}
.button-container{
    display: flex;
    justify-content: space-between; // 两个按钮之间的间距
    margin-bottom: 4px; // 按钮和表单之间的间距
}
// 左上角按钮
.button1{

}
.button2{

}
.qr-code{
    width: 200px; // 二维码图片宽度
    height: 200px; // 二维码图片高度
    border: 1px solid #ccc; // 二维码图片边框
    border-radius: 10px; // 二维码图片圆角
    display: flex;
    justify-content: center; // 二维码图片水平居中
    margin-top: 20px; // 二维码和表单之间的间距
}
.other-login{
    margin-top: 20px; // 其他登录和二维码之间的间距
    display: flex;
    justify-content: center; // 其他登录内容水平居中
    flex-direction: column; // 竖直方向布局
    align-items: center; // 内容水平居中
}
.other-login p {
    transform: translateY(-20px); // 文字垂直居中
    margin: 10px 0; // 其他登录内容之间的间距
    color: #472424; // 文字颜色
    font-size: 14px; // 字体大小
}
.two-login{

}
.form-container{
    width: 100%;
    display: flex;
    flex-direction: column; // 竖直方向布局
    align-items: center; // 内容水平居中
  
}
h2 {
    margin-bottom: 2px; // 标题和表单之间的间距
    font-size: 24px;
    font-weight: 600;
    color: #1a1a1a;
}
.demo-ruleForm{
    margin-top: 20px;
    display: flex;
    flex-direction: column;
    align-items: center; // 两个按钮之间的间距
}
.demo2-ruleForm{
    display: flex;
    justify-content: space-between; // 两个按钮之间的间距
   
}
</style>